<?php

namespace App\Libraries;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;

class MicrosoftSpeech
{
    protected $key = 'c4a07c9bf019498693225f7a71b79bc4';
    // 获取音频库
    public function getVoices()
    {
        $headers = [
            "Ocp-Apim-Subscription-Key" => $this->key
        ];

        $client = new Client();
        $response = $client->get('https://eastus.tts.speech.microsoft.com/cognitiveservices/voices/list', [
            'headers' => $headers
        ]);

        if ($response->getStatusCode() != 200) {
            return [];
        }

        return json_decode($response->getBody()->getContents(), true);
    }

    // 调用文字转语音接口
    public function textToSpeech($ssmlBody)
    {
        $uri = 'https://eastus.tts.speech.microsoft.com/cognitiveservices/v1';
        return $this->request($uri, $ssmlBody);
    }

    public function speechToText($audio_file)
    {
        $uri = 'https://eastus.tts.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';
        $audio_data = file_get_contents($audio_file);
        return $this->request($uri, $audio_data);
    }

    public function request($uri, $body)
    {
        try {
            $headers = [
                "Ocp-Apim-Subscription-Key" => $this->key,
                "Content-Type" => "application/ssml+xml",
                "X-Microsoft-OutputFormat" => "riff-24khz-16bit-mono-pcm"
            ];
            $client = new Client([
                'timeout'  => 300, // 设置请求超时时间为300秒
                'connect_timeout' => 5, // 设置连接超时时间为5秒
            ]);
            $response = $client->post($uri, [
                'headers' => $headers,
                'body' => $body
            ]);
            if ($response->getStatusCode() != 200) {
                return false;
            }

            return $response->getBody()->getContents();
        } catch (RequestException $e) {
            dd($e->getMessage());
            return false;
        } catch (ConnectException $e) {
            dd($e->getMessage());
            return false;
        }
    }
}
